package com.liangzhen.verynews.data;

import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.liangzhen.verynews.bean.News;

public class ParseNewsData {
	
	private ArrayList<News> newslist = new ArrayList<News>();
	public static JSONObject ParseJson(final String path, final String encode) {
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(path);
		try {
			HttpResponse httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity(),
						encode);
				JSONObject jsonObject = new JSONObject(result);
				return jsonObject;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpClient != null)
				httpClient.getConnectionManager().shutdown();
		}
		return null;
	}
	
	public ArrayList<News> getNewsList(String path){
		JSONObject json = ParseNewsData.ParseJson(path, "utf-8");
		try {
			JSONObject Data = json.getJSONObject("data");
			for (int i = 0; i <= 19; i++) {
				JSONObject Article = Data.getJSONObject("" + i);
				News news = new News();
				news.setTitle(Article.getString("title"));
				news.setImage("http://www.3dmgame.com"
						+ Article.getString("litpic"));
				news.setClick(Article.getString("click"));
				news.setDate(Article.getString("pubdate"));
				news.setId(Article.getString("id"));
				newslist.add(news);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return newslist;
	}
}
